#include "robot.h"


Robot::Robot()
{
    QString strPorc = SYSCONF.robotPath;

    qDebug() << SYSCONF.robotPath;

    m_pProc = new QProcess();
    m_pProc->setReadChannel(QProcess::StandardOutput);
    m_pProc->start(strPorc);

    connect(m_pProc, SIGNAL(readyReadStandardOutput()), this, SLOT(recvStandOut()));
}

void Robot::recvStandOut()
{
    exec();
}

QString Robot::answer()
{
    return m_strQuestion;
}

void Robot::run() {
    QByteArray byte = question.toLocal8Bit();
    const char *pChar = byte.data();
    m_pProc->write(pChar);
    m_pProc->write("\r\n");
    qDebug() << m_pProc->waitForBytesWritten(2000);
}

void Robot::setQuestion(QString strQuestion) {
    //向IKNOW.exe发送消息
    question = strQuestion;
}

QString Robot::strQuestion() const
{
    return m_strQuestion;
}

void Robot::setStrQuestion(const QString &strQuestion)
{
    m_strQuestion = strQuestion;
}

bool Robot::findAnswer()
{
    //收到IKNOW.exe的消息

    QByteArray byte = m_pProc->readAllStandardOutput();
    //QTextCodec *pTextCodec = QTextCodec::codecForName("unicode");
    //QString strMsg = pTextCodec->toUnicode(byte);
    QString strMsg = byte;
    qDebug() << strMsg;
    if (strMsg.isEmpty()) {
        return false;
    }
    //用换车替换{br}
    strMsg.replace("{br}", QChar('\n'));

    m_strQuestion = strMsg;
    return true;
}

void Robot::exec()
{
    if (findAnswer()) {
        qDebug() << "findAnswer!";
        emit reRobotMsg();
    }
}
